package com.zxl.intecepter;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.zxl.constants.DatasourceConstants;
import com.zxl.constants.RedisConstants;
import com.zxl.utils.StringUtils;
import com.zxl.vo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @packageName com.zxl.intecepter
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Component
public class DataSourceInterceptor implements HandlerInterceptor {
    @Autowired
    private StringUtils stringUtils;

    @Value("${datasource-number}")
    private Integer datasource_number;

    @Value("${table-number}")
    private Integer table_number;


    private ThreadLocal<String> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户信息
        Customer customer = (Customer) request.getSession().getAttribute(RedisConstants.USER_LOGIN_SESSION_KEY);
        int i = Integer.parseInt(stringUtils.getId(customer.getId()));
        //根据用户信息得到要使用的数据源

        Integer dataSourceId = i % datasource_number;
        DynamicDataSourceContextHolder.push(DatasourceConstants.DATASOUURCE + dataSourceId);

        //根据用户信息得到要使用的数据库表单的序号并存入到ThreadLocal中
        Integer tableId = i / datasource_number % table_number + 1;
        threadLocal.set(tableId.toString());
        return true;
    }

    public ThreadLocal<String> getThreadLocal() {
        return threadLocal;
    }
}
